package com.sea.base.utils

import android.os.Looper
import android.view.WindowManager
import com.sea.base.ext.global.logE
import com.sea.base.ext.global.postMain

/**
 * hook一些无用或可忽略的异常，不可忽略的异常禁止拦截
 *
 * @作者 王能
 */
object LoopHookUtil {
    private const val TAG = "LoopHookUtil"

    @JvmStatic
    fun hookInit() {
        postMain {
            //while可减少栈的层数
            while (true) {
                try {
                    Looper.loop()
                } catch (e: Throwable) {
                    val traceList = exToStringList(e)
                    when {
                        isToast(e, traceList) -> {
                            "已hook无用的Toast异常".logE(TAG)
                            e.printStackTrace()
                            //继续loop
                            continue
                        }
                    }
                    //其他异常不做处理
                    throw e
                }
            }
        }
    }

    /**
     * toast崩溃
     */
    private fun isToast(e: Throwable, traceList: List<String>): Boolean {
        when (e) {
            is IllegalStateException, is IllegalArgumentException, is WindowManager.BadTokenException -> {
                if (listContains(traceList, "android.widget.Toast\$TN")) {
                    return true
                }
            }
        }
        return false
    }

    /**
     * @return 有一个contains则返回true
     */
    private fun listContains(traceList: List<String>, st: String): Boolean {
        traceList.forEach {
            if (it.contains(st)) {
                return true
            }
        }
        return false
    }

    private fun exToStringList(e: Throwable): List<String> {
        val st = e.stackTraceToString()
        val list = ArrayList<String>(st.split("\n"))
        list.forEachIndexed { index, s ->
            list[index] = s.trim()
        }
        return list
    }
}